<template>
  <div class="scheduled-tasks">
    <div class="header">
      <h2>定时任务管理</h2>
      <el-button type="primary" @click="handleCreate">创建任务</el-button>
    </div>

    <!-- 任务表格 -->
    <el-table :data="tasks" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="任务名称" min-width="150" />
      <el-table-column prop="task_type" label="任务类型" width="150">
        <template #default="{ row }">
          {{ getTaskTypeLabel(row.task_type) }}
        </template>
      </el-table-column>
      <el-table-column prop="cron_expression" label="Cron表达式" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="last_run" label="上次执行时间" width="180">
        <template #default="{ row }">
          {{ row.last_run ? formatDate(row.last_run) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleExecute(row)">执行</el-button>
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 任务编辑对话框 -->
    <el-dialog
      v-model="showEditModal"
      :title="currentTask ? '编辑定时任务' : '创建定时任务'"
      width="600px"
    >
      <el-form :model="editForm" label-width="100px" ref="editFormRef">
        <el-form-item label="任务名称" prop="name" :rules="[{ required: true, message: '请输入任务名称', trigger: 'blur' }]">
          <el-input v-model="editForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="task_type" :rules="[{ required: true, message: '请选择任务类型', trigger: 'change' }]">
          <el-select v-model="editForm.task_type" placeholder="请选择任务类型" style="width: 100%">
            <el-option label="健康资讯爬虫" value="news_crawler" />
            <el-option label="敏感词更新" value="words_crawler" />
            <el-option label="帖子审核" value="post_review" />
          </el-select>
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cron_expression" :rules="[{ required: true, message: '请输入Cron表达式', trigger: 'blur' }]">
          <el-input v-model="editForm.cron_expression" placeholder="请输入Cron表达式" />
          <div style="margin-top: 10px;">
            <el-button size="small" @click="showCronGenerator = !showCronGenerator">
              {{ showCronGenerator ? '隐藏生成器' : '使用生成器' }}
            </el-button>
          </div>
          <div v-if="showCronGenerator" style="margin-top: 10px;">
            <CronElementPlus 
              v-model="editForm.cron_expression" 
              @change="handleCronChange"
              locale="zh"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="激活" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditModal">取消</el-button>
        <el-button type="primary" @click="saveTask" :loading="isSaving">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CronElementPlus } from '@vue-js-cron/element-plus'
import '@vue-js-cron/element-plus/dist/element-plus.css'
import request from '@/api/request'

const loading = ref(false)
const showEditModal = ref(false)
const isSaving = ref(false)
const currentTask = ref<any>(null)
const editFormRef = ref<any>(null)
const showCronGenerator = ref(false)

const editForm = reactive({
  name: '',
  task_type: '',
  cron_expression: '',
  status: 'inactive'
})

const tasks = ref<any[]>([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取任务类型标签
const getTaskTypeLabel = (type: string) => {
  const types: Record<string, string> = {
    'news_crawler': '健康资讯爬虫',
    'words_crawler': '敏感词更新',
    'post_review': '帖子审核'
  }
  return types[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'inactive':
      return 'info'
    default:
      return 'info'
  }
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statuses: Record<string, string> = {
    'active': '激活',
    'inactive': '停用'
  }
  return statuses[status] || status
}

// 处理cron表达式变化
const handleCronChange = (value: string) => {
  editForm.cron_expression = value
}

// 获取任务列表
const fetchTasks = async (page = 1) => {
  loading.value = true
  try {
    const params = {
      page: page,
      page_size: pagination.size
    }
    
    const response = await request.get('/health/scheduled-tasks/', { params })
    tasks.value = response.results || []
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取定时任务列表失败')
  } finally {
    loading.value = false
  }
}

// 创建任务
const handleCreate = () => {
  currentTask.value = null
  Object.assign(editForm, {
    name: '',
    task_type: '',
    cron_expression: '',
    status: 'inactive'
  })
  showCronGenerator.value = false
  showEditModal.value = true
}

// 编辑任务
const handleEdit = (task: any) => {
  currentTask.value = task
  Object.assign(editForm, {
    name: task.name,
    task_type: task.task_type,
    cron_expression: task.cron_expression,
    status: task.status
  })
  showCronGenerator.value = false
  showEditModal.value = true
}

// 关闭编辑弹窗
const closeEditModal = () => {
  showEditModal.value = false
  currentTask.value = null
  showCronGenerator.value = false
}

// 保存任务
const saveTask = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
  } catch (error) {
    return
  }
  
  isSaving.value = true
  try {
    if (currentTask.value) {
      // 更新任务
      await request.patch(`/health/scheduled-tasks/${currentTask.value.id}/`, editForm)
      ElMessage.success('更新成功')
    } else {
      // 创建任务
      await request.post('/health/scheduled-tasks/', editForm)
      ElMessage.success('创建成功')
    }
    
    // 更新列表
    fetchTasks()
    closeEditModal()
  } catch (error) {
    ElMessage.error(currentTask.value ? '更新任务失败' : '创建任务失败')
  } finally {
    isSaving.value = false
  }
}

// 删除任务
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除该定时任务吗？', '提示', {
      type: 'warning'
    })
    
    await request.delete(`/health/scheduled-tasks/${row.id}/`)
    ElMessage.success('删除成功')
    fetchTasks()
  } catch (error) {
    // 用户取消删除或删除失败
  }
}

// 执行任务
const handleExecute = async (row: any) => {
  try {
    await request.post(`/health/scheduled-tasks/${row.id}/execute/`)
    ElMessage.success('任务执行成功')
    fetchTasks()
  } catch (error) {
    ElMessage.error('任务执行失败')
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.size = val
  fetchTasks()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchTasks(val)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.scheduled-tasks {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>